package com.upupwe.raspberry.app.update;

import android.app.IntentService;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.upupwe.raspberry.BuildConfig;
import com.upupwe.raspberry.R;
import com.upupwe.raspberry.app.utils.Constant;
import com.upupwe.raspberry.app.utils.RxBus;
import com.upupwe.raspberry.mvp.model.entity.Version;

import java.io.File;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

public class UpdateApkService extends IntentService {

    private static Context mContext;

    public static final String ACTION_DOWNLOAD = "intentservice.ACTION_DOWNLOAD";

    public static final String APK_PATH = "APK_PATH";

    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotificationManager;
    private static String apkPath;

    public UpdateApkService() {
        super("UpdateApkService");
    }


    public static void startUpdateService(Context context) {
        mContext = context;
        Intent intent = new Intent(context, UpdateApkService.class);
        intent.setPackage(context.getPackageName());
        intent.setAction(ACTION_DOWNLOAD);
        String apkPath = Constant.APP_ROOT_PATH + context.getPackageName() + Constant.DOWNLOAD_DIR + BuildConfig.App_FileName;
        intent.putExtra(APK_PATH, apkPath);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            if (ACTION_DOWNLOAD.equals(action)) {
                if (BuildConfig.DEBUG) {
                    UpdateManager.JumpMain(mContext);
                } else {
                    //订阅下载
                    subscribeDownload(intent);
                    //判断是否需要更新版本
                    if (UpdateManager.checkUpdate(mContext)) {

                        //UpdateManager.downLoadApk(this, apkPath, null);
                    }
                }
            }
        }
    }

    protected void subscribeDownload(Intent intent) {
        RxBus.getDefault().toObservable(Version.class)
                .subscribe(new Observer<Version>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Version version) {
                        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        mBuilder = new NotificationCompat.Builder(UpdateApkService.this)
                                .setSmallIcon(R.mipmap.ic_launcher_round)
                                .setContentTitle("下载最新版中")
                                .setProgress(100, 0, false)
                                .setAutoCancel(true);
                        mNotificationManager.notify(0, mBuilder.build());
                        apkPath = intent.getStringExtra(APK_PATH);
                        subscribeProgress();//订阅下载进度
                        if (version.getVersionCode() > BuildConfig.VERSION_CODE) {
                            UpdateManager.downLoadApk(UpdateApkService.this, apkPath, mCompositeDisposable);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void subscribeProgress() {
        RxBus.getDefault().toObservable(ApkLoadingBean.class)
                .subscribe(new Observer<ApkLoadingBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("test", "onSubscribe: ");
                        mCompositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(ApkLoadingBean bean) {
                        int progress = (int) Math.round(bean.getProgress() / (double) bean.getTotal() * 100);
                        mBuilder.setProgress(100, progress, false);
                        mNotificationManager.notify(0, mBuilder.build());
                        mBuilder.setContentTitle("下载进度：" + progress + "%");
                        if (progress == 100) {
                            mNotificationManager.cancel(0);
                            install(apkPath);
                        }
                        Timber.i("progress:" + progress);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mBuilder.setContentTitle("下载出错！");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    boolean install(String filePath) {
        try {
            if (TextUtils.isEmpty(filePath))
                return false;
            File file = new File(filePath);
            if (!file.exists()) {
                return false;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//增加读写权限
            }
            intent.setDataAndType(getPathUri(mContext, filePath), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(mContext, "安装失败，请重新下载", Toast.LENGTH_LONG).show();
            return false;
        } catch (Error error) {
            Toast.makeText(mContext, "安装失败，请重新下载", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    public static Uri getPathUri(Context context, String filePath) {
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String packageName = context.getPackageName();
            uri = FileProvider.getUriForFile(context, packageName + ".fileProvider", new File(filePath));
        } else {
            uri = Uri.fromFile(new File(filePath));
        }
        return uri;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
